<?php
namespace app\myadmin\model;
use think\Model;
class menu extends Model
{
	// 时间戳配置
	protected $autoWriteTimestamp = true;
	// 定义时间戳字段名
	protected $createTime = "create_time";
	protected $updateTime = "update_time";
	// 列表
	public function index($where=[])
	{
		$menuList = $this
			->where($where)
			->order("pid asc,orders asc,id asc")
			->select();
		$menuList = $this->buildMenuChild(0, $menuList);
		return $menuList;
	}
	// 递归
	private function buildMenuChild($pid, $menuList)
	{
		$treeList = [];
		foreach ($menuList as $k=>$v) {
			if($v["module"]!="" && $v["controller"]!="" && $v["function"]!=""){
				$v["href"]=$v["module"]."/".$v["controller"]."/".$v["function"];
			}else{
				$v["href"]="";
			}
			if($k==0){
				$v["spread"]=true;
			}
			if ($pid == $v["pid"]) {
				$node = $v;
				$children = $this->buildMenuChild($v["id"], $menuList);
				if (!empty($children)) {
					$node["children"] = $children;
				}
				$treeList[] = $node;
			}
		}
		return $treeList;
	}
	// 增改
	public function edit($Int,$Data)
	{
		$Data=TrimArray($Data);
		$validate = new \app\myadmin\validate\Menu;
		$Data["orders"] = intval($Data["orders"])?:0;
		if (!$validate->check($Data)) {
			return ["code"=>1,"msg"=>$validate->getError()];
		}
		if($Int==0){
			$info=$this->save($Data);
		}else{
			$info=$this->update($Data);
		}
		if($info){
			return ["code"=>0,"msg"=>"操作成功"];
		}else{
			return ["code"=>1,"msg"=>"操作失败"];
		}
	}
}
